# -*- coding: utf-8 -*-
# @Time        :2025/4/17 16:33
# @Author      :文刀水寿
# @File        : urls.py
"""
 @Description :
"""
from fastapi import APIRouter, File, UploadFile
from typing import List
import os


app5 = APIRouter()


@app5.post('/file')
async def file(file: UploadFile):
    print("file", file)
    return {
        "file": "file"
    }


@app5.post('/files')
async def upload_files(files: List[UploadFile]):
    try:
        folder_path = "img"
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)  # 确保文件夹存在

        file_names = []
        for file in files:
            print(f"File name: {file.filename}, Content type: {file.content_type}")

            # 检查文件名是否冲突，避免覆盖
            base_name, extension = os.path.splitext(file.filename)
            counter = 1
            new_filename = file.filename
            while os.path.exists(os.path.join(folder_path, new_filename)):
                new_filename = f"{base_name}_{counter}{extension}"
                counter += 1

            # 保存文件
            path = os.path.join(folder_path, new_filename)
            with open(path, "wb") as f:
                f.write(await file.read())

            file_names.append(new_filename)

        return {
            "message": "Files uploaded successfully",
            "file_names": file_names
        }
    except Exception as e:
        print(f"An error occurred: {e}")
        return {"error": "Internal Server Error"}